// pages/traincar/order.js
var util = require('../../utils/util.js');
const app = getApp();
var isclick = 1;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showTopTips: false,
    errorMsg: "",
    listInfo: [],
    bannerUrl:'',
    submitname: '预约教练',
    isshow: false,
    today: '',
    tomorrow: '',
    tomorrow1: '',
    tomorrow2: '',
    week1: '',
    week2: '',
    week3: '',
    week4: '',
    typeArr: ['专人专车', '拼团陪练'],
    seltypeinfo: '',
    tindex:1,
    vindex: 1,
    iindex: 1,
    seldateArr: [],
    seldatainfo: '',
    hourArr: ['1', '2', '3', '4'],
    selhourinfo: '',
    paymoney:0,
    zrzc:50,
    ptpl:30,
    areas: [],
    areaIndex: 0,
    towns: [],
    townIndex: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getDatelist();
    this.setData({
        selhourinfo: this.data.hourArr[this.data.iindex - 1],
        seldatainfo: this.data.seldateArr[this.data.iindex],
        seltypeinfo: this.data.typeArr[this.data.tindex - 1],
    })
    this.getprice();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var uid = wx.getStorageSync('userId');
    wx.request({
      url: app.globalData.hostUrl + 'member/getfansinfo',
      data: {
        id: uid
      },
      success: function (res) {
        var name = res.data.result.realname;
        var mobile = res.data.result.phone;
        if (name == '' || mobile == '') {
          wx.showModal({
            content: '对不起，请先填写【个人资料】中的真实姓名和手机号码！',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '../myself/info',
                })
              }
            }
          });
        }
      }
    })
    this.setData({
      listInfo: app.globalData.listInfo
    })
    //检查已经预约的信息
    this.initBanner();
    this.getAreas();
  },
    //广告图片初始化
    initBanner: function () {
        var that = this;
        var requrl = app.globalData.hostUrl + 'common/banner';
        var imgbanner = wx.getStorageSync('trainBanner');
        //console.log(imgbanner.length);
        if (!app.expiratTime('trainBanner') || imgbanner.length == 0) {
            wx.request({
                url: requrl,
                data: { 'location': '203' },
                header: {
                    'grant-appid': app.globalData.appid
                },
                success: function (res) {
                    if (res.statusCode === 200) {
                        wx.setStorageSync('trainBanner', res.data.result[0].imgpath);
                        that.setData({
                            bannerUrl: res.data.result[0].imgpath
                        })
                    }
                }
            })
        }
        else {
            that.setData({
                bannerUrl: imgbanner
            })
        }
    },
  getAreas: function () {
    var that = this;
    var requrl = app.globalData.hostUrl + 'common/getAreas';
    var areasArr = ['-请选择-'];
    wx.request({
      url: requrl,
      success: function (res) {
        //console.log(res);
        if (res.statusCode === 200) {
          var areaslist = res.data.result;
          var areasMap = areaslist.map(item => {
            return item.name;
          });
          areasArr = areasArr.concat(areasMap);
          that.setData({
            areas: areasArr,
            areaslist
          });
        }
      }
    })

  },
  getTowns: function () {
    var that = this;
    var requrl = app.globalData.hostUrl + 'common/getTwopids';
    var townsArr = ['-请选择-'];
    var aindex = this.data.areaIndex;
    if (parseInt(aindex) > 0) {
      aindex = parseInt(aindex) - 1;
      var aid = this.data.areaslist[aindex].id;
      wx.request({
        url: requrl,
        data: { 'pid': aid },
        header: {
          'grant-appid': app.globalData.appid
        },
        success: function (res) {
        //  console.log(res);
          if (res.statusCode === 200) {
            var townslist = res.data.result;
            var townsMap = townslist.map(item => {
              return item.name;
            });
            townsArr = townsArr.concat(townsMap);
            that.setData({
              towns: townsArr,
              townslist
            });
          }
        }
      })
    }
  },  
  bindareasChange: function (e) {
    var that=this;
    util.clearError(that);
    this.setData({
      areaIndex: e.detail.value
    })
    this.getTowns();
  },
  bindtownsChange: function (e) {
    var that = this;
    util.clearError(that);
    this.setData({
      townIndex: e.detail.value
    })
  },
  //获得陪练价格  
  getprice:function(){
    var that=this;
    var requrl = app.globalData.hostUrl + 'handler/getPlprice';
    var hour = that.data.hourArr[that.data.iindex - 1];
    var type = that.data.tindex;
    var money = 0;
    wx.request({
      url: requrl,
      success: function (res) {
//        console.log(res);
        if (res.data.code == 200) {
          var zrzc = res.data.result.zrzc;
          var ptpl = res.data.result.ptpl;
          if (type == 1) {
            money = hour * zrzc;
          }
          else if (type == 2) {
            money = hour * ptpl;
          }
          that.setData({
            zrzc:zrzc,
            ptpl: ptpl,
            paymoney: money
          })
        }
      }
    })
  },  
  cancel:function(){
      var hour = this.data.hourArr[this.data.iindex - 1];
      var type = this.data.tindex;
      var money=0;
      if(type==1){
          money=hour * this.data.zrzc;
      }
      else if(type==2){
        money = hour * this.data.ptpl;
      }
      this.setData({
          paymoney: money
      })
  },
  selv: function (e) {
    var index = e.currentTarget.dataset.vid;
    this.setData({
      vindex: index,
      seldatainfo: this.data.seldateArr[index]
    })
    this.cancel();
  },
  selitem: function (e) {
    var index = e.currentTarget.dataset.iid;
    this.setData({
      iindex: index,
      selhourinfo: this.data.hourArr[index-1]
    })
    this.cancel();
  },
  seltype: function (e) {
    var index = e.currentTarget.dataset.tid;
    this.setData({
        tindex: index,
        seltypeinfo: this.data.typeArr[index - 1]
    })
    this.cancel();
  },
  getDatelist: function () {
    var dateArr = [];
    var plandate = [];
    for (var i = 0; i < 4; i++) {
      var date = new Date();
      date.setTime(date.getTime() + i * 24 * 60 * 60 * 1000);

      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var day = date.getDate()

      if (month < 10)
        month = '0' + month;
      if (day < 10)
        day = '0' + day;

      var datename = month + "-" + day;
      var tomorrow_full = year + "-" + datename;
      plandate.push(tomorrow_full);
      var week = new Date(tomorrow_full).getDay();
      if (i == 0) {
        var week1 = this.changeWeek(week);
        this.setData({
          today: datename,
          week1: week1
        })
        dateArr[i] = datename + ' 星期' + week1;
      }
      else if (i == 1) {
        var week2 = this.changeWeek(week);
        this.setData({
          tomorrow: datename,
          week2: week2
        })
        dateArr[i] = datename + ' 星期' + week2;
      }
      else if (i == 2) {
        var week3 = this.changeWeek(week);
        this.setData({
          tomorrow1: datename,
          week3: week3
        })
        dateArr[i] = datename + ' 星期' + week3;
      }
      else if (i == 3) {
        var week4 = this.changeWeek(week);
        this.setData({
          tomorrow2: datename,
          week4: week4
        })
        dateArr[i] = datename + ' 星期' + week4;
      }
    }
    this.setData({
      seldateArr: dateArr,
      plantime: plandate
    })
  },
  changeWeek: function (week) {
    var weekname = '';
    switch (week) {
      case 0:
        weekname = '日';
        break;
      case 1:
        weekname = '一';
        break;
      case 2:
        weekname = '二';
        break;
      case 3:
        weekname = '三';
        break;
      case 4:
        weekname = '四';
        break;
      case 5:
        weekname = '五';
        break;
      case 6:
        weekname = '六';
        break;
    }
    return weekname;
  },
 
  formSubmit: function (e) {
    var that=this;
    var requrl = app.globalData.hostUrl + 'handler/trainlc';
    if (this.data.areaIndex > 0)
      var areaid = this.data.areaslist[this.data.areaIndex - 1].id;
    else {
      util.isError("选择报名区域!", that);
      return false;
    }

    if (this.data.townIndex > 0)
      var townid = this.data.townslist[this.data.townIndex - 1].id;
    else {
      util.isError("选择报名区域!", that);
      return false;
    }  

    var postdata = {
      'userid': wx.getStorageSync('userId'),
      'planinfo': this.data.seldatainfo + ' ' + this.data.seltypeinfo + ' ' + (this.data.selhourinfo != '' ? this.data.selhourinfo + '小时' : ''),
      'plantime': this.data.plantime[this.data.vindex],
      'xhour': this.data.hourArr[this.data.iindex],
      'type': this.data.tindex,
      'money': this.data.paymoney,
      'areaid': areaid,
      'townid': townid,
      'openid': wx.getStorageSync('openId'),
      'formid': e.detail.formId
    }
    //console.log(postdata);
    
    if (isclick == 1) {
      isclick = 0;
      wx.request({
        url: requrl,
        data: postdata,
        header: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'grant-appid': app.globalData.appid
        },
        method: 'POST',
        success: function (res) {
//          console.log(res);
          if (res.data.code == 200) {
            var orderid = res.data.result;
            wx.showModal({
              title: '提示',
              content: '提交订单成功',
              success(res) {
                  wx.navigateTo({
                    url: '../traincar/orderdetail?oid=' + orderid
                  })
              }
            })
          }
          else if (res.data.code == 201) {
            wx.showToast({
                title: '订单失败',
              icon: 'error',
              duration: 2000
            })
            isclick = 1;
          }
          else if (res.data.code == 202) {
            wx.showToast({
                title: '订单已存在',
              icon: 'success',
              duration: 2000
            })
            isclick = 1;
          }
          else if (res.data.code == 204) {
            wx.showModal({
              title: '提示',
              content: '获取用户信息失败',
              success(res) {
                wx.redirectTo({
                  url: '/pages/wxauth/wxauth',
                })
              }
            })
            isclick = 1;
          }
        }
      })
    }
  },
  calling: function (e) {
    var mobile = '15916351997';
    wx.makePhoneCall({
      phoneNumber: mobile,
      success: function () {
        //console.log("拨打电话成功！")
      },
      fail: function () {
        // console.log("拨打电话失败！")
      }
    })
  },
  gohome: function () {
    wx.redirectTo({
      url: '../index/index',
    })
  },
  yuy: function () {
    if (1 == wx.getStorageSync('roleidentity')) {
      wx.redirectTo({
        url: '../myself/thappointment',
      })
    }
    else {
      wx.redirectTo({
        url: '../myself/myappointment',
      })
    }
  },
  orders: function () {
    if (1 == wx.getStorageSync('roleidentity')) {
      wx.redirectTo({
        url: '../myself/trorder',
      })
    }
    else {
      wx.redirectTo({
        url: '../myself/myorder',
      })
    }
  },
  mys: function () {
    wx.redirectTo({
      url: '../myself/myself',
    })
  },
  onShareAppMessage: function () {

  }
})